<template>
  <a-modal
    title="修改登录密码"
    :visible="visible"
    :width="500"
    :mask-closable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :rules="rules" :model="form">
      <a-form-item field="old_password" label="原密码">
        <a-input-password
          v-model="form.old_password"
          placeholder="请输入原密码"
        />
      </a-form-item>
      <a-form-item field="password" label="新密码">
        <a-input-password v-model="form.password" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item field="password_confirmation" label="确认密码">
        <a-input-password
          v-model="form.password_confirmation"
          placeholder="请输入确认密码"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { updatePasswordApi } from '@/api/user';

  defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
  });
  const emit = defineEmits(['ok', 'cancel']);
  const form = ref({
    old_password: '',
    password: '',
    password_confirmation: '',
  });
  const rules = {
    old_password: [
      {
        required: true,
        message: '请输入原密码',
      },
      {
        minLength: 6,
        message: '密码最少6位',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入新密码',
      },
      {
        minLength: 6,
        message: '密码最少6位',
      },
    ],
    password_confirmation: [
      {
        required: true,
        message: '请输入确认密码',
      },
      {
        minLength: 6,
        message: '密码最少6位',
      },
      {
        validator: (value: string, cb: any) => {
          if (value !== form.value.password) {
            cb('确认密码和新密码不一致');
          } else {
            cb();
          }
        },
      },
    ],
  };
  const formRef = ref();
  const handleOk = () => {
    formRef.value
      .validate()
      .then((result: any) => {
        if (result) {
          Message.info({
            content: '请输入必填项',
            duration: 3 * 1000,
          });
          return;
        }
        updatePasswordApi(form.value)
          .then(() => {
            Message.success({
              content: '成功',
              duration: 3 * 1000,
            });
            // 提交
            emit('ok');
          })
          .catch((error: any) => {
            Message.error({
              content: error.message,
              duration: 3 * 1000,
            });
          });
      })
      .catch(() => {
        // error
      });
  };
  const handleCancel = () => {
    emit('cancel');
  };
</script>
